package com.kj.mynote.Activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.TimePickerView;
import com.kj.mynote.Bean.NoteBean;
import com.kj.mynote.Bean.NoteDeptBean;
import com.kj.mynote.R;
import com.kj.mynote.Util.AutoUtils;
import com.kj.mynote.Util.FileUtils;
import com.kj.mynote.Util.ToolUtils;
import com.wang.avi.AVLoadingIndicatorView;

import org.litepal.crud.DataSupport;
import org.w3c.dom.Text;

import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


/**
 * @author wy
 * @version V1.0
 * @Title: MyApplication
 * @Package com.kj.mynote
 * @Description: TODO(用一句话描述该文件做什么)
 * @date 17/3/21 15:00
 */

public class NoteEditActivity extends BaseActivity {
    EditText etNote;
    TextView btnTJ, tvSTime, tvETime, tvClass, tvTitle;
    ImageView back;
    AVLoadingIndicatorView loading;
    LinearLayout btnClass;
    ListView lv;
    String title, date, fileName, noteClass = "默认分组";
    int num;//字數
    long startTime, endTime;//开始时间 结束时间
    PopupWindow pwClass;
    List<NoteDeptBean> data;
    DeptListAdapter adapter;
    String str = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_note_edit);
        AutoUtils.auto(this);
        init();
        linstener();
    }

    private void init() {
        tvTitle = (TextView) findViewById(R.id.note_et_title);
        tvTitle.setText("新建便签");
        btnTJ = (TextView) findViewById(R.id.note_et_btn_tj);
        tvSTime = (TextView) findViewById(R.id.note_et_stime);
        tvETime = (TextView) findViewById(R.id.note_et_etime);
        tvClass = (TextView) findViewById(R.id.note_et_tv_class);
        etNote = (EditText) findViewById(R.id.note_et);
        btnClass = (LinearLayout) findViewById(R.id.note_et_btn_class);
        back = (ImageView) findViewById(R.id.note_et_back);
        loading = (AVLoadingIndicatorView) findViewById(R.id.note_et_loading);
        startTime = System.currentTimeMillis();
        String time = ToolUtils.TS2S(new Long(startTime), "yyyy-MM-dd HH:mm");
        tvSTime.setText(time);
        FileUtils.createFolder(new File(FileUtils.noteMRDir));
        searchDept();
    }

    private void linstener() {
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (str.length() == 0) {
                    finish();
                } else {
                    showTDialog("退出后您输入的内容不会保存，确认退出吗?", 0);
                }
            }
        });
        etNote.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                str = etNote.getText().toString();
                str = str.replaceAll("[\\n\\r]*", "");
                num = str.length();
            }
        });
        btnTJ.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                endTime = System.currentTimeMillis();
                if (str.length() == 0) {
                    Toast.makeText(NoteEditActivity.this, "请输入内容后提交", Toast.LENGTH_LONG).show();
                } else {
                    if (str.length() > 10) {
                        title = etNote.getText().subSequence(0, 10) + "...";
                    } else {
                        title = str;
                    }
                    showTDialog("确定提交么？本次工作共进行" + ToolUtils.TS2TS(startTime, endTime), 1);
                }
            }
        });
        btnClass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopu(v);
            }
        });
        tvSTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initTimeView(0);
            }
        });
        tvETime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initTimeView(1);
            }
        });
    }

    private void showPopu(View v) {
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.layout_pop_class, null);
        contentView.findViewById(R.id.note_group_btn_add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pwClass.dismiss();
                showEDialog();
            }
        });
        lv = (ListView) contentView.findViewById(R.id.note_group_list);
        adapter = new DeptListAdapter();
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                updateDept(data.get(position).getDeptName());
            }
        });
        AutoUtils.auto(contentView);
        pwClass = new PopupWindow(contentView,
                LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        pwClass.setBackgroundDrawable(getResources().getDrawable(R.drawable.pop_background));
        pwClass.showAtLocation(v, Gravity.CENTER, 0, 0);
    }

    private void showEDialog() {
        final EditText newName = new EditText(NoteEditActivity.this);
        newName.setLines(1);
        AlertDialog.Builder inputDialog =
                new AlertDialog.Builder(NoteEditActivity.this);
        inputDialog.setTitle("输入新的分组名").setView(newName);
        inputDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String name = newName.getText().toString().trim();
                        List<NoteDeptBean> list = DataSupport.where("deptName=?", name).find(NoteDeptBean.class);
                        if (list.size() == 1) {
                            Toast.makeText(NoteEditActivity.this, "已经有该的分组", Toast.LENGTH_LONG).show();
                        } else {
                            File dirFile = new File(FileUtils.rootTxtDir + name);
                            boolean flag = FileUtils.createFolder(dirFile);
                            if (flag) {
                                saveDept(name);
                            } else {
                                Toast.makeText(NoteEditActivity.this, "保存分组失败", Toast.LENGTH_LONG).show();
                            }
                        }
                        searchDept();
                        updateDept(name);
                    }
                }).show();
    }

    private void showTDialog(String title, final int i) {
        final AlertDialog.Builder tipDialog =
                new AlertDialog.Builder(NoteEditActivity.this);
        tipDialog.setTitle(title);
        tipDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (i == 0) {
                            dialog.dismiss();
                            finish();
                        } else {
                            dialog.dismiss();
                            fileName = noteClass + "_" + ToolUtils.TS2S(new Long(startTime), "yyyy-MM-dd") + "_" + startTime + ".txt";
                            new saveFile().execute(etNote.getText().toString());
                        }
                    }
                });
        tipDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        tipDialog.show();
    }

    private void saveDept(String name) {
        NoteDeptBean bean = new NoteDeptBean();
        bean.setDeptName(name);
        bean.save();
    }

    private void searchDept() {
        data = DataSupport.findAll(NoteDeptBean.class);
        NoteDeptBean b = new NoteDeptBean();
        b.setDeptName("默认分组");
        b.setId(0);
        data.add(0, b);
    }

    private void updateDept(String name) {
        noteClass = name;
        tvClass.setText(noteClass);
        pwClass.dismiss();
    }

    private boolean saveNote() {
        NoteBean note = new NoteBean();
        note.setTitle(title);
        note.setStartTime(startTime);
        note.setEndTime(endTime);
        note.setNoteClass(noteClass);
        note.setFilePath(FileUtils.rootTxtDir + noteClass + "/" + fileName);
        note.setNum(num);
        return note.save();
    }

    class saveFile extends AsyncTask<String, String, Boolean> {

        @Override
        protected Boolean doInBackground(String... params) {
            boolean flag1 = FileUtils.writeFile(params[0], noteClass, fileName);
            boolean flag2 = saveNote();
            if(flag1){
                Log.e("flag1","flag1");
            }
            if(flag2){
                Log.e("flag","flag2");
            }
            return flag1 && flag2;
        }

        @Override
        protected void onPostExecute(Boolean flag) {
            super.onPostExecute(flag);
            loading.setVisibility(View.GONE);
            if (flag) {
                Toast.makeText(NoteEditActivity.this, "保存成功", Toast.LENGTH_LONG).show();
                setResult(RESULT_OK);
                finish();
            } else {
                Toast.makeText(NoteEditActivity.this, "保存失败，请重试", Toast.LENGTH_LONG).show();
            }

        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loading.setVisibility(View.VISIBLE);
        }
    }

    class ViewHolder {
        TextView tvName;
        ImageView ivSelect;
    }

    class DeptListAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return data.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = LayoutInflater.from(NoteEditActivity.this).inflate(R.layout.item_note_group, null);
                AutoUtils.auto(convertView);
                viewHolder.tvName = (TextView) convertView.findViewById(R.id.note_group_tv_name);
                viewHolder.ivSelect = (ImageView) convertView.findViewById(R.id.note_group_iv_select);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            String name = data.get(position).getDeptName();
            viewHolder.tvName.setText(name);
            if (name.equals(noteClass)) {
                viewHolder.ivSelect.setVisibility(View.VISIBLE);
            } else {
                viewHolder.ivSelect.setVisibility(View.GONE);
            }
            return convertView;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (str.length() == 0) {
                finish();
            } else {
                showTDialog("退出后您输入的内容不会保存，确认退出吗?", 0);
            }
        }
        return false;
    }

    public void initTimeView(final int i) {
        TimePickerView pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调]
                if (i == 0) {
                    startTime = new Long(date.getTime());
                    tvSTime.setText(ToolUtils.TS2S(startTime, "yyyy-MM-dd HH:mm:ss"));
                } else {
                    endTime = new Long(date.getTime());
                    tvETime.setText(ToolUtils.TS2S(endTime, "yyyy-MM-dd HH:mm:ss"));
                }
            }
        })
                .setLineSpacingMultiplier(2)
                .build();
        pvTime.setDate(Calendar.getInstance());
        pvTime.show();
    }
}
